/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.fanli.ui;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.CashbackManager.CashbackTask;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.DownloadItem;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.common.widget.MarqueeTextView;

/**
 * 返利平台产品详细页面
 */
public class TaskInformationActivity extends BaseActivity implements
    OnClickListener, ApiRequestListener, Observer {

  private RelativeLayout mActionBar;
  private ImageView mActionIcon;
  private TextView mActionLabel;
  
  /**
   * 产品详细
   */
  private RebateTask mRebateTask;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fanli_activity_taskinformation);

    mRebateTask = (RebateTask) getIntent().getSerializableExtra(
        Constants.EXTRA_PRDUCT_DETAIL);
    if (mRebateTask == null) {
      // show error
      return;
    }

    initViewsByTheme();
    initTopBar(mRebateTask);
    initDescriptionView(mRebateTask);
    initActionBar();

    if (mSession.cashbackManager != null) {
      HashMap<String, CashbackTask> tasks = mSession.cashbackManager
          .getRebateTasks();
      if (tasks != null && tasks.get(mRebateTask.pkgName) != null) {
        mRebateTask.status = tasks.get(mRebateTask.pkgName).status;
      }
      mSession.cashbackManager.addObserver(this);
    }
    toogleStatus(mRebateTask.status);
  }
  
  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mSession.cashbackManager != null) {
      mSession.cashbackManager.deleteObserver(this);
    }
  }

  /**
   * 初始化当前主题下的资源
   */
  private void initViewsByTheme() {
    mActionBar = (RelativeLayout) findViewById(R.id.action_btn_left);
    mActionBar.setBackgroundResource(ThemeManager.getResource(mSession,
        ThemeManager.KEY_ACTION_BAR_OPERATION_BG));
    TextView actionText = (TextView) findViewById(R.id.tv_left);
    actionText.setTextAppearance(getApplicationContext(),
        ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
    mActionBar.setOnClickListener(this);
  }

  /**
   * 初始化下载动作按钮
   */
  private void initActionBar() {
    mActionIcon = (ImageView) findViewById(R.id.iv_left);
    mActionIcon.setImageResource(ThemeManager.getResource(mSession,
        ThemeManager.KEY_ACTION_BAR_START));
    mActionLabel = (TextView) findViewById(R.id.tv_left);
    mActionLabel.setText(R.string.label_start_download);
  }
  
  @Override
  @SuppressWarnings("unchecked")
  public void update(Observable observable, Object data) {
    
    if (data instanceof HashMap) {
      
      HashMap<String, CashbackTask> tasks = (HashMap<String, CashbackTask>) data;
      
      CashbackTask task = tasks.get(mRebateTask.pkgName);
      if (task != null) {
        Utils.D("get status > " + task.status);
        mRebateTask.status = task.status;
        toogleStatus(task.status);
      } else {
        Utils.D("not get status ");
      }
    }
  }
  
  /**
   * 切换操作状态
   */
  private void toogleStatus(int status) {

    switch (status) {
      case RebateTask.STATUS_NORMAL:

        mActionBar.setEnabled(true);
        mActionIcon.setImageResource(R.drawable.action_bar_download);
        mActionLabel.setText(R.string.tab_download);
        break;
        
      case RebateTask.STATUS_DOWNLOADING:

        mActionBar.setEnabled(false);
        mActionIcon.setImageResource(R.drawable.action_bar_downloading);
        mActionLabel.setText(R.string.download_status_downloading);
        break;
        
      case RebateTask.STATUS_DOWNLOADED:

        mActionBar.setEnabled(true);
        mActionIcon.setImageResource(R.drawable.action_bar_install);
        mActionLabel.setText(R.string.download_status_downloaded);
        break;
        
      case RebateTask.STATUS_INSTALLED:
        
        mActionBar.setEnabled(false);
        mActionIcon.setImageResource(R.drawable.action_bar_uninstall);
        mActionLabel.setText(R.string.download_status_pending);
        break;
        
      case RebateTask.STATUS_REBATED:

        mActionBar.setEnabled(false);
        mActionIcon.setImageResource(R.drawable.rebated);
        mActionLabel.setText(R.string.download_status_rebated);
        break;
        
      case RebateTask.STATUS_INVALID:
        
        mActionBar.setEnabled(false);
        mActionIcon.setImageResource(R.drawable.action_bar_uninstall);
        mActionLabel.setText(R.string.download_status_invalid);
        break;

      default:
        
        mActionBar.setEnabled(false);
        break;
    }
  }

  /*
   * 初始化TopBar
   */
  private void initTopBar(final RebateTask product) {

    TextView bg = (TextView) findViewById(R.id.topbar);
    bg.setBackgroundResource(ThemeManager.getResource(mSession,
        ThemeManager.KEY_TOP_BAR_BG));

    RelativeLayout bottom_bg = (RelativeLayout) findViewById(R.id.rl_bg_bottom);
    bottom_bg.setBackgroundResource(ThemeManager.getResource(mSession,
        ThemeManager.KEY_TOP_BAR_BG));

    final ImageView ivIcon = (ImageView) findViewById(R.id.iv_icon);
    ImageUtils.download(getApplicationContext(), product.iconUrl, ivIcon,
        false);

    final MarqueeTextView tvName = (MarqueeTextView) findViewById(R.id.tv_name);
    tvName.setTextAppearance(getApplicationContext(),
        ThemeManager.getResource(mSession, ThemeManager.KEY_TOP_TITLE_TEXT));
    if (mSession.getTheme() == ThemeManager.THEME_TYPE_DARK) {
      tvName.setShadowLayer(0.1f, 0, -2.0f, Color.BLACK);
    }
    tvName.setText(product.taskName);
  }
  
  /*
   * 初始化产品描述信息
   */
  private void initDescriptionView(RebateTask product) {

    TextView price = (TextView) findViewById(R.id.tv_info);
    price.setText(getString(R.string.pay_unit,
        Utils.convertCentToYuan(product.rebateMoney)));
    
    TextView longDescription = (TextView) findViewById(R.id.app_description2);
    longDescription.setText(product.description);
    longDescription.setOnClickListener(this);
    
    ImageView banner = (ImageView) findViewById(R.id.iv_pic);
    ImageUtils.downloadCpaImage(getApplicationContext(),
        product.bannerUrl, banner);
    
    TextView type = (TextView) findViewById(R.id.tv_task);
    type.setText(product.taskType);

  }
  
  @Override
  public void onSuccess(int method, Object obj) {
    if (MarketAPI.ACTION_GET_DOWNLOAD_URL == method) {
      DownloadItem info = (DownloadItem) obj;
      mSession.cashbackManager.startTask(info.url, info.packageName,
          mRebateTask.taskName);
    }
  }

  @Override
  public void onError(int method, int statusCode) {
    // TODO Auto-generated method stub
    
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

      case R.id.action_btn_left:

        if (mRebateTask.status == RebateTask.STATUS_DOWNLOADED) {
          // 安装
          Utils.trackEvent(getApplicationContext(), Constants.GROUP_REBATE,
              Constants.REBATE_CLICK_INSTALL_2);
          mSession.cashbackManager.install(mRebateTask.pkgName);
        } else if (mRebateTask.status == RebateTask.STATUS_NORMAL) {
          // 点击下载按钮
          Utils.trackEvent(getApplicationContext(), Constants.GROUP_REBATE,
              Constants.REBATE_CLICK_DOWNLOAD_2);
          MarketAPI.getDownloadUrl(getApplicationContext(), this,
              mRebateTask.taskId, Constants.SOURCE_TYPE_REBATE);
        }
        break;

      default:
        break;
    }
  }

  
  /**
   * 返利任务详细信息.
   */
  public static class RebateTask implements Serializable {
    
    private static final long serialVersionUID = -1210982667395725602L;

    /**
     * 未安装
     */
    public static final int STATUS_NORMAL = 0;
    
    /**
     * 已安装(返利平台)<br>
     * 审核中状态
     */
    public static final int STATUS_INSTALLED = 1;
    
    /**
     * 已返利
     */
    public static final int STATUS_REBATED = 2;

    /**
     * 返利失败
     */
    public static final int STATUS_FAIL = 3;
    
    /**
     * 已下载，未安装
     */
    public static final int STATUS_DOWNLOADED = 4;
    
    /**
     * 下载中
     */
    public static final int STATUS_DOWNLOADING = 5;
    
    /**
     * 已安装(非返利平台)<br>
     * 无效任务
     */
    public static final int STATUS_INVALID = 9;
    
    /**
     * 返利任务ID
     */
    public String taskId;
    
    /**
     * 返利任务名->应用名
     */
    public String taskName;
    
    /**
     * 包名
     */
    public String pkgName;
    
    /**
     * 产品推广图
     */
    public String bannerUrl;
    
    /**
     * 产品ICON
     */
    public String iconUrl;
    
    /**
     * 任务类型
     */
    public String taskType;
    
    /**
     * 返还金额
     */
    public int rebateMoney;
    
    /**
     * 描述信息
     */
    public String description;
    
    /**
     * 返利任务状态，状态值为以下四种:<br>
     * 1- {@link #STATUS_NORMAL}<br>
     * 2- {@link #STATUS_INSTALLED}<br>
     * 3- {@link #STATUS_REBATED}<br>
     * 4- {@link #STATUS_INVALID}<br>
     */
    public int status;
    

    @Override
    public String toString() {
      return this.taskName + " > " + this.status;
    }
    
  }

}
